<?php

namespace app\modules\api\helper;

use linslin\yii2\curl;
use Yii;

class UccHelper
{

    /**
     * 请求句柄
     * @var linslin\yii2\curl\Curl
     */
    protected $handle = null;
    /**
     * 查询服务地址
     */
    const URL = 'http://ucc-apiv2.uuzu.com/ucc_api/index.php';
    /**
     * 指定访问 ip
     */
    const HOST_IP = '10.6.48.139';
    /**
     * 请求默认设置项
     * @var array
     */
    protected $CurlOption = [
        CURLOPT_URL => self::URL,
        CURLOPT_HTTPHEADER => self::HOST_IP,
        CURLOPT_SSL_VERIFYHOST=> false,
        CURLOPT_SSL_VERIFYPEER=> false,
        CURLOPT_HEADER=> 0,
        CURLOPT_POST=> 1,
        CURLOPT_RETURNTRANSFER=> 1,
        CURLOPT_USERAGENT => 'PHP 7 Curl Base DeskTop Tools',
    ];
    /**
     * 接口请求参数列表
     * @var array
     */
    protected $QueryData = [
        'server' => [
            'service'=>'server.getServerListInfo',
            'server_id'=>'1422310583',
            'filter'=>'business.server_key,business.opgame_id,business.business_type,business.business_id,'
                .'business.business_neme,business.business_num,business.business_url,business.pay_url,'
                .'business.business_opentime,business.kfsystem_status,business.max_online,business.op_id,'
                .'business.game_id,business.obj_id,business.is_hide,business.ssx,business.ssy,business.update_time',
        ],
        'department'=>[
            'service'=>'department.getList',
        ],
        'game'=>[
            'service'=>'game.getList',
            'type'=>'list',
            // 'game_id'=>'146',
            // 'server_id'=>'146',
            // 'op_id'=>'146',
            'game_play_type'=>'1',
        ],
    ];

    /**
     * 查询错误 码
     * @var integer
     */
    protected $QueryErrCode = 200;
    /**
     * 查询错误 信息
     * @var string
     */
    protected $QueryErrMsg = '';
    /**
     * 缓存有效期
     * @var int
     */
    public $cacheExpire = 60 * 30;
    /**
     * 是否使用缓存
     * @var boolean
     */
    public $UseCache = true;
    /**
     * 设置选项
     * @return linslin\yii2\curl\Curl 返回句柄
     */
    public function addOption($option, $val = null)
    {
        return is_array($option) ?
            $this->initOptiom($option) :
            $this->getHandler()->setOption($option, $val);
    }
    /**
     * 获取查询句柄
     * @return   linslin\yii2\curl\Curl 返回句柄
     */
    protected function getHandler()
    {
        return $this->handle ?? new curl\Curl();
    }
    /**
     * 发起查询
     * @param  array $param 查询参数
     * @return string       查询结果
     */
    public function query($param)
    {
        $handle = $this->getHandler();
        $this->QueryErrCode = 200;
        # 缓存
        $cache = $this->cache($param);
        if ($cache and $this->UseCache) {
            return $cache;
        }
        $handle
            ->setOption(CURLOPT_POSTFIELDS, http_build_query($param))
            ->post(self::URL);
        $response = $this->dealRep($handle);
        if ($response) {
            $this->cache($param, $response);
        }
        return $response;
    }
    /**
     * 处理请求结果
     * @param linslin\yii2\curl\Curl $handle 请求句柄
     * @return  mixed 处理结果
     */
    protected function dealRep($handle)
    {
        if ($handle->responseCode === 200) {
            $response = json_decode($handle->response, true);
            if ($response['ret'] === 200) {
                return $response['data'];
            } else {
                $this->QueryErrCode = (int)('100' . $response['ret']);
                $this->QueryErrMsg = $response['msg'];
            }
        }
        return false;
    }
    /**
     * 初始化请求参数
     */
    public function __construct()
    {
        $this->init();
        $this->initOptiom($this->CurlOption);
        return $this;
    }
    /**
     * 初始化请求参数
     */
    protected function initOptiom($option)
    {
        $handler = $this->getHandler();
        foreach ($option as $opt => $val) {
            $handler->setOption($opt, $val);
        }
        return $handler;
    }
    /**
     * 初始化方法
     */
    protected function init()
    {
    }

    /**
     * 获取请求相关信息
     * @param  string $name 属性名
     * @return mixed           值
     */
    public function __get($name)
    {
        $handler = $this->getHandler();
        return isset($handler->$name) ?? null;
    }

    /**
     * 根据配置文件组装参数进行查询
     * @param  string     $method 方法名
     * @param  array     $args   参数
     * @return mixed    查询结果
     */
    public function __call($method, $args)
    {
        if (empty($this->QueryData[$method])) {
            $this->QueryErrCode = 0;
            $this->QueryErrMsg = Yii::t('app', 'unknow service');
            return false;
        }
        $QueryData = $this->QueryData[$method];
        if (is_array(current($args))) {
            $QueryData = array_merge($QueryData, current($args));
        }
        return $this->query($QueryData);
    }

    /**
     * 获取错误码
     * @return int 错误码
     */
    public function getErrCode()
    {
        if ($this->QueryErrCode === 200) {
            return $this->errorCode;
        }
        return $this->QueryErrCode;
    }
    /**
     * 获取错误码信息
     * @return int 错误码
     */
    public function getErrMsg()
    {
        if ($this->QueryErrCode === 200) {
            return $this->errorText;
        }
        return $this->QueryErrMsg;
    }
    /**
     * 查询结果缓存操作
     * @param  mixed     $key     缓存key
     * @param  mixed     $val     值
     * @return mixed    结果
     */
    protected function cache($key, $val = null)
    {
        if (is_array($key)) {
            $key = http_build_query($key);
        }
        $key = md5($key);
        $cache = Yii::$app->cache;
        if (empty($val)) {
            $data = $cache->get($key, false);
            return $data;
        } else {
            $cache->set($key, $val, $this->cacheExpire);
            return $val;
        }
    }

    public function useCache($useCache)
    {
        $this->UseCache = $useCache;
        return $this;
    }
}
